<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="部门名称"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="getQueryDepartments">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="this.pageInfo.dataList" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="120" sortable>
			</el-table-column>
			<el-table-column prop="manager.username" label="主管" width="100"  sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="父部门" width="100" sortable>
			</el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" sortable>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180" sortable>
      </el-table-column>
			<el-table-column prop="path" label="路径" width="120" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" min-width="180" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state==1" style="color: #11b95c">启用</span>
          <span v-else style="color: red">禁用</span>
        </template>
			</el-table-column>
      <el-table-column prop="intro" label="介绍" min-width="180" sortable>
      </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
		<!--	<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="this.query.pageSize" :total="this.pageInfo.total" style="float:right;">
			</el-pagination>-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="this.query.currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          style="float:right;"
          :total="this.pageInfo.total">
      </el-pagination>
		</el-col>

	

    <!--
      只有弹出模态框有这个问题 就是 v-model 绑定显示 不行 需要换成另一种写法 :visible.sync
      :rules="saveFormRules"  是规则
    -->
		<!--新增/修改界面-->
		<el-dialog title="新增/修改" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="部门经理" prop="manager">
          <el-select v-model="saveForm.manager" clearable value-key="id" placeholder="请选择">
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"
            -->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
            </el-option>
          </el-select>
				</el-form-item>
        <el-form-item label="上级部门" prop="parent">
          <el-cascader v-model="saveForm.parent"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>
				<el-form-item label="部门简绍" prop="intro">
					<el-input type="textarea" v-model="saveForm.intro"></el-input>
				</el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'


	export default {
		data() {
			return {
        query: {
					keyword: '',
          currentPage:1,
          pageSize:10
				},
        pageInfo:{
          dataList: [],
          total: 0
        },
				page: 1,
				listLoading: false,
				sels: [],//列表选中列




				saveFormVisible: false,//新增界面是否显示
				addLoading: false,
				saveFormRules: {
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					]
				},
				//新增界面数据
				saveForm: {
          id:null,
          name:"",
          intro:"",
          manager:{
            id:null,
            username:""
          },
          parent:{
            id:null,
            name:""
          },
          state:""
				},
        // 定义管理员数据
        employees:[],
        // 定义父部门数据
        deptTree:[]
			}
		},
		methods: {
      // 查询父部门数据
      getDeptTree(){
        this.$http.get("/department/deptTree")
            .then(result=>{
              result = result.data
              if (result.success){
                // console.log(result.resultObj);
                this.deptTree =result.resultObj;
              }else{

              }
            })
            .catch(result=>{
              // 这里的catch是发请求都出了问题

            })
      },
		  // 查询管理员数据
      getEmployees(){
        this.$http.get("/employee")
            .then(result=>{
              result = result.data
              if (result.success){
                this.employees = result.resultObj;

              }else{

              }
            })
            .catch(result=>{
              // 这里的catch是发请求都出了问题

            })
      },
      handleSizeChange(val){
        this.query.pageSize = val;
        this.getDepartments()
      },
		  // 点击查询按钮
      getQueryDepartments(){
        this.query.currentPage = 1
        this.getDepartments()
      },

			handleCurrentChange(val) {
				this.query.currentPage = val;
        this.getDepartments()
			},
			//获取部门列表
			getDepartments() {
        // No 'Access-Control-Allow-Origin'
        // 只要看到浏览器报这个错误就是跨域问题 前后端分离的项目一定会有跨越问题
				this.listLoading = true;
        // 发请求
        // localhost:8080/department  全局的前缀

        this.$http.put("/department",this.query)
            .then(result=>{
              result = result.data
              if (result.success){
                this.$message({message: '查询成功', type: 'success' });
                this.listLoading = false;
                this.pageInfo = result.resultObj
                console.log(this.pageInfo.dataList);
              }else{

              }
            })
            .catch(result=>{

            })

			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true; // 模态框
					//NProgress.start();
					let para = { id: row.id };
					//发请求
          this.$http.delete("/department/"+row.id)
          .then(result=>{
            result = result.data
            if (result.success){
              this.$message({message: '删除成功', type: 'success' });
              this.listLoading = false;
              this.query.currentPage = 1;
              // 刷新列表
              this.getDepartments()
            }else{
              this.$message({message: '删除失败', type: 'danger' });
            }
          })
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.saveFormVisible = true;
        this.getEmployees()
        this.getDeptTree()
				this.saveForm = Object.assign({}, row);// 将行数据  赋值给  saveForm
        console.log(this.saveForm.manager.id);
        if (!row.parent){
          this.saveForm.parent={
            id:null,
            name:""
          }
        }
        if (!row.manager){
          this.saveForm.manager={
            id:null,
            username:""
          }
        }
        // 处理 级联下拉框回显
        var path = row.path;
        var split = path.split("/");
        var p = [];
        for (let i = 1; i < split.length-1; i++) {
          p.push(Number.parseInt(split[i]))
          this.saveForm.parent = p
        }
        console.log("parent:"+this.saveForm.parent);
        this.saveForm.state = Number.parseInt(row.state)

			},
			//显示新增界面
			handleAdd: function () {
				this.saveFormVisible = true;
				this.saveForm = {
          id:null,
          name:"",
          intro:"",
          manager:{
            id:null,
            username:""
          },
          parent:{
            id:null,
            name:""
          },
          state:""
        }
        this.getEmployees()
        this.getDeptTree()

			},

			//新增
			addSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							let para = Object.assign({}, this.saveForm); // json格式的转换
              // 处理父级级联框
              var parent = this.saveForm.parent;

              if (parent && parent.length>0){
                var id = parent[parent.length-1]
                para.parent={
                  id:id,
                }
              }
              // 发请求
              this.$http.post("/department",para)
              .then(result=>{
                result = result.data
                if (result.success){
                  this.$message({message: '保存成功', type: 'success' });
                  this.addLoading = false;
                  this.saveFormVisible = false
                  // 刷新列表
                  this.getDepartments()
                }else{
                  this.$message({message: '保存失败', type: 'danger' });
                }
              })
              .catch(result=>{
                  // 这里的catch是发请求都出了问题
                  this.$message({message: '网络异常,请检查您的网络', type: 'danger' });
              })
            }).catch({})


					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					// 发请求
          this.$http.patch("/department",ids)
              .then(result=>{
                result = result.data
                if (result.success){
                  this.$message({message: '批量删除成功', type: 'success' });
                  this.listLoading = false;
                  this.query.currentPage = 1;
                  // 刷新列表
                  this.getDepartments()
                }else{
                  this.$message({message: '批量删除失败', type: 'danger' });
                }
              })
              .catch(result=>{

              })
          })
          .catch(() => {

          });
			}
		},
		mounted() {
			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>